package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by 沐风 on 2024/4/16 10:51
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private UserMapper userMapper;
    /**
     * 用户登录
     * @param userLoginDTO
     * @return
     */
    @Override
    public User login(UserLoginDTO userLoginDTO) {
        //调用方法获得openid
        String openid = getOpenid(userLoginDTO.getCode());

        //如果openid为空，则登录失败
        if (openid == null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }

        //判断是否是第一次登录小程序，如果是新用户，自动注册，把信息存入数据库中
        User user = userMapper.getByOpenid(openid);
        if (user == null){
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insert(user);
        }

        return user;
    }

    /**
     * 向微信接口服务发送请求获取openid
     * @param code
     * @return
     */
    private String getOpenid(String code){
        Map<String, String> claim = new HashMap<>();
        claim.put("appid", weChatProperties.getAppid());
        claim.put("secret", weChatProperties.getSecret());
        claim.put("js_code",code);
        claim.put("grant_type","authorization_code");
        String json = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/jscode2session", claim);
        JSONObject jsonObject = JSON.parseObject(json);//将json格式的数据转换为java对象
        String openid = jsonObject.getString("openid");
        return openid;
    }
}
